package net.hmr_radio.hmrbot.controller.login;

import net.hmr_radio.hmrbot.model.Bot;
import net.hmr_radio.hmrbot.model.UserInfo;
import net.hmr_radio.hmrbot.service.BotService;
import net.hmr_radio.hmrbot.service.UserInfoService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

public class ByTwitterSuccessController extends Controller {

    private BotService botService = new BotService();
    private UserInfoService userInfoService = new UserInfoService();

    @Override
    public Navigation run() throws Exception {
        String accessToken = requestScope("accessToken");
        String accessTokenSecret = requestScope("accessTokenSecret");

        Twitter twitter;
        try {
            twitter = TwitterFactory.getSingleton();
            twitter.setOAuthAccessToken(new AccessToken(
                accessToken,
                accessTokenSecret));
            twitter.getHomeTimeline();
        } catch (Exception e) {
            return forward("/login/error");
        }

        Bot bot = botService.get(twitter);
        if (bot == null) {
            botService.createNewBot(twitter);
        }
        UserInfo user = userInfoService.get(bot);
        if (user == null) {
            // ユーザー情報が存在しない場合、新規ユーザー作成
            // 新規ユーザーのuserIdはBotのscreen_nameとなる
            user = userInfoService.createNewUser(twitter);
        }

        request.getSession().invalidate();
        sessionScope("loginUser", user);
        sessionScope("twitter", twitter);

        return redirect("/mypage/");
    }
}
